package com.redxiii.spike.pmi.command;

import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;

import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.redxiii.spike.api.command.CommandFactory;
import com.redxiii.spike.api.command.InitializationRequired;
import com.redxiii.spike.api.pmi.entity.Issue;
import com.redxiii.spike.util.message.BasicMsgInterpreter;

/**
 * @author Daniel Filgueiras
 * 17/11/2011
 */
@InitializationRequired
@CommandFactory(BasicMsgInterpreter.class)
public class LiveIssues extends ShowIssues {

	private static final Logger logger = LoggerFactory.getLogger(LiveIssues.class);
	
	private static Comparator<Issue> recentOrder = new Comparator<Issue>() {
		@Override
		public int compare(Issue o1, Issue o2) {
			
			if (o1.getUpdatedOn() == null || o2.getUpdatedOn() == null)
				return o1.compareTo(o2);
			
			int resp = o2.getUpdatedOn().compareTo(o1.getUpdatedOn());
			if (resp == 0)
				return o1.compareTo(o2);
			
			return resp;
		}
	};
	
	@Override
	protected SortedSet<Issue> filterIssues(SortedSet<Issue> issues) {
		
		issues = super.filterIssues(issues);
		
		Date lastWeek = new DateTime().minusWeeks(1).withMillisOfDay(0).toDate();
		
		SortedSet<Issue> sortedIssues = new TreeSet<Issue>(recentOrder);
		
		Iterator<Issue> iterator = issues.iterator();
		while (iterator.hasNext()) {
			Issue issue = iterator.next();
			
			if (issue.getUpdatedOn() == null || issue.getUpdatedOn().after(lastWeek)) {
				sortedIssues.add(issue);
			} else {
				logger.debug("Issue id {} discarted", issue.getId());
			}
		}
		
		return sortedIssues;
	}
}
